//
//  CYPlayerView.m
//  lianxi
//
//  Created by 曹宇 on 16/7/14.
//  Copyright © 2016年 caoyu. All rights reserved.
//

#import "CYPlayerView.h"
#import "Masonry.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "ZFDownloadManager.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

// 枚举值，包含水平移动方向和垂直移动方向
typedef NS_ENUM(NSInteger, PanDirection){
    PanDirectionHorizontalMoved, //横向移动
    PanDirectionVerticalMoved    //纵向移动
};


@interface CYPlayerView ()<UIGestureRecognizerDelegate>
@property (nonatomic, copy)   NSString        *totalTime;
@property (nonatomic, retain) NSDateFormatter *dateFormatter;
@property (nonatomic, retain) UIButton        *buttonOfState;
@property (nonatomic, retain) UILabel         *labelOfTime;
@property (nonatomic, retain) UILabel         *labelOfTime2;
@property (nonatomic, retain) id              playbackTimeObserver;
@property (nonatomic, retain) UISlider        *videoSlider;
@property (nonatomic, retain) UIProgressView  *videoProgress;
@property (nonatomic, assign) BOOL            played;
@property (nonatomic, assign) BOOL            isTap;
@property (nonatomic, assign) BOOL            doubleTap;
@property (nonatomic, retain) NSURL           *url;
@property (nonatomic, retain) UIButton        *buttonOfFullScreen;
@property (nonatomic, retain) UILabel         *labelOfTitle;

@property (nonatomic, assign) BOOL            buttonOfShowisSelected;


/** 定义一个实例变量，保存枚举值 */
@property (nonatomic, assign) PanDirection        panDirection;

/** 用来保存快进的总时长 */
@property (nonatomic, assign) CGFloat             sumTime;

/** 是否在调节音量*/
@property (nonatomic, assign) BOOL                isVolume;

/** 滑杆 */
@property (nonatomic, strong) UISlider            *volumeViewSlider;
/** 滑动时显示的时间 */
@property (nonatomic, retain)UILabel *labelOfMove;

@end

@implementation CYPlayerView

#pragma mark - 更改layer,重写set,get方法
//由于默认的layer是CALayer，而AVPlayer只能添加至AVPlayerLayer中，所以改变一下layerClass，这样PlayerView的默认layer就变了，之后我们可以把在viewController中初始化的AVPlayer对象赋给AVPlayerLayer的player属性。
+ (Class)layerClass {
    return [AVPlayerLayer class];
}

//重写了set和get方法，用于将player添加至playerView的AVPlayerLayer中，这样才能顺利将视频显示出来
- (AVPlayer *)player {
    return [(AVPlayerLayer *)[self layer] player];
}

- (void)setPlayer:(AVPlayer *)player {
    [(AVPlayerLayer *)[self layer] setPlayer:player];
}


#pragma mark - 初始化
- (instancetype)init{
    self = [super init];
    if (self) {
        self.cy_mArrOfURL = [NSMutableArray array];
        [self addGestureRecognizer];
        [self createButton];
        [self configDefinition];
        [self configureVolume];
        
        [self configNextVideoButton];
        //切换声道
//        AVAudioSession *session = [AVAudioSession sharedInstance];
//        
//        [session setCategory:AVAudioSessionCategoryPlayAndRecord
//                 withOptions:AVAudioSessionCategoryOptionMixWithOthers
//                       error:nil];
        
        
    }
    return self;
}

#pragma mark - public
- (void)cy_playerViewLabel:(NSString *)str{
    
    self.labelOfTitle = [[UILabel alloc]init];
    self.labelOfTitle.text = str;
    self.labelOfTitle.textColor = [UIColor whiteColor];
    [self addSubview:self.labelOfTitle];
    [self.labelOfTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(70);
        make.right.equalTo(self.mas_right).with.offset(-50);
        make.top.equalTo(self.mas_top).with.offset(15);
        make.height.mas_equalTo(@20);
    }];
}

#pragma mark - AVPlayer(public)
- (void)cy_playerViewURl:(NSURL *)url{

    self.url = url;
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    
    /** 添加观察者,观察status属性(status有三种状态：
     AVPlayerStatusUnknown,
     AVPlayerStatusReadyToPlay,
     AVPlayerStatusFailed) */
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    //添加观察者,观察loadedTimeRanges属性(loadedTimeRange属性代表已经缓冲的进度，监听此属性可以在UI中更新缓冲进度)
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    //建立avplayer
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    //暂停播放按钮
    self.buttonOfState.enabled = NO;
    
    self.player.volume= 1.0;
    
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    
    //  注册观察者来观察屏幕的旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    
    //progressVIew显示缓冲的可播放区域
    self.videoProgress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    [self addSubview:self.videoProgress];
    
    [self.videoProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(80);
        make.right.equalTo(self.mas_right).with.offset(-80);
        make.bottom.equalTo(self.mas_bottom).with.offset(-15);
        make.height.mas_equalTo(@2);
    }];

    //timelabel
    self.labelOfTime = [[UILabel alloc]init];
    self.labelOfTime2 = [[UILabel alloc]init];
    self.labelOfTime.textColor = [UIColor whiteColor];
    self.labelOfTime2.textColor = [UIColor whiteColor];
    self.labelOfTime.font = [UIFont systemFontOfSize:13];
    self.labelOfTime2.font = [UIFont systemFontOfSize:13];
    self.labelOfTime.textAlignment = NSTextAlignmentCenter;
    self.labelOfTime2.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.labelOfTime];
    [self addSubview:self.labelOfTime2];
    [self.labelOfTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right);
        make.bottom.equalTo(self.mas_bottom).with.offset(-2);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    [self.labelOfTime2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.bottom.equalTo(self.mas_bottom).with.offset(-2);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    
    self.labelOfMove = [[UILabel alloc]init];
    self.labelOfMove.textColor = [UIColor whiteColor];
    self.labelOfMove.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    self.labelOfMove.font = [UIFont systemFontOfSize:16];
    self.labelOfMove.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.labelOfMove];
    [self.labelOfMove mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY).with.offset(80);
        make.size.mas_equalTo(CGSizeMake(150, 40));
    }];
    
    self.labelOfMove.hidden = YES;
    
    [self.player play];
    [self.buttonOfState setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    
    
    
    
}
#pragma mark - 视频播放结束回到开始时间
- (void)moviePlayDidEnd:(NSNotification *)notification {
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        [weakSelf.videoSlider setValue:0.0 animated:YES];
        [weakSelf.buttonOfState setBackgroundImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
//        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
    }];
}

#pragma mark - 播放页面添加单击,双击手势
- (void)addGestureRecognizer {
    //单击
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews:)];
    [oneTap setNumberOfTapsRequired:1];
    [self addGestureRecognizer:oneTap];
    //双击
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    [self addGestureRecognizer:doubleTap];
    
    //  只有当没有检测到doubleTap 或者 检测doubleTap失败，singleTapGestureRecognizer才有效
    [oneTap requireGestureRecognizerToFail:doubleTap];
}

//隐藏控件
-(void)dismissAllSubViews:(UIGestureRecognizer *)sender{
    
    if (!self.isTap) {
        
        [UIView animateWithDuration:0.8 animations:^{
            self.videoSlider.alpha = 0;
            self.buttonOfState.alpha = 0;
            self.labelOfTime.alpha = 0;
            self.labelOfTime2.alpha = 0;
            self.videoProgress.alpha = 0;
            self.buttonOfFullScreen.alpha = 0;
            self.labelOfTitle.alpha = 0;
            self.buttonOfShow.alpha = 0;
            self.buttonOfHide.alpha = 0;
            self.buttonOfDown.alpha = 0;
            self.buttonOfReturn.alpha = 0;
        }];
    }else{
        [UIView animateWithDuration:0.8 animations:^{
            self.videoSlider.alpha = 1;
            self.buttonOfState.alpha = 1;
            self.labelOfTime.alpha = 1;
            self.labelOfTime2.alpha = 1;
            self.videoProgress.alpha = 1;
            self.buttonOfFullScreen.alpha = 1;
            self.labelOfTitle.alpha = 1;
            self.buttonOfShow.alpha = 1;
            self.buttonOfHide.alpha = 1;
            self.buttonOfDown.alpha = 1;
            self.buttonOfReturn.alpha = 1;
        }];

        
    }
    self.isTap = !self.isTap;
   
}

//双击手势
- (void)handleDoubleTap:(UIGestureRecognizer *)sender{
    if (self.doubleTap == NO) {
        [self.player play];
        [self.buttonOfState setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    }else{
        [self.player pause];
        [self.buttonOfState setBackgroundImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    }
    self.doubleTap = !self.doubleTap;
}

#pragma mark - 横屏 竖屏的时候frame的设置
- (void)statusBarOrientationChange:(NSNotification *)notification {
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        [self setHorizontalFrame];
    }
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        [self setHorizontalFrame];
    }
//    if (orientation == UIInterfaceOrientationPortrait) {
//        [self setVerticalFrame];
//    }
}

//  横屏的时候frame
- (void)setHorizontalFrame {
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}

//  竖屏的时候frame
//- (void)setVerticalFrame {
//    self.frame = CGRectMake(0, 20, SCREEN_WIDTH, 235);
//}

#pragma mark - 添加一个通知，用于监听视频是否已经播放完毕，然后实现KVO的方法
/** 此方法主要对status和loadedTimeRanges属性做出响应，status状态变为AVPlayerStatusReadyToPlay时，说明视频已经可以播放了，这时我们可以获取一些视频的信息，包含视频长度等，把播放按钮设备enabled，点击就可以调用play方法播放视频了 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            self.buttonOfState.enabled = YES;
            // 加载完成后，再添加平移手势
            // 添加平移手势，用来控制音量、亮度、快进快退
            UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panDirection:)];
            pan.delegate                = self;
            [self addGestureRecognizer:pan];
            

            
            //获取视频总长度
            CMTime duration = self.playerItem.duration;
            //转换成秒
            CGFloat totalSecond = CMTimeGetSeconds(duration);
            //转换成播放时间
            self.totalTime = [self convertTime:totalSecond];
            //自定义slider
         
                [self customVideoSlider:duration];

            //监听播放状态
            [self monitoringPlayback:self.playerItem];
            
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            //播放失败;
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        //计算缓冲进度
        NSTimeInterval timeInterval = [self availableDuration];
        CMTime duration = self.playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        //用UIProgressView显示缓冲的可播放区域
        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
    }
}

//时间转换
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}

/** monitoringPlayback用于监听每秒的状态，- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;此方法就是关键，interval参数为响应的间隔时间，这里设为每秒都响应，queue是队列，传NULL代表在主线程执行。可以更新一个UI，比如进度条的当前时间等。 */
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    __weak typeof(self) weakSelf = self;
    self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        //计算当前在第几秒
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;
        //根据时间改变slider的值
        [weakSelf.videoSlider setValue:currentSecond animated:YES];
        //显示播放时长和总时长
        NSString *timeString = [weakSelf convertTime:currentSecond];
        weakSelf.labelOfTime.text = [NSString stringWithFormat:@"%@",weakSelf.totalTime];
        weakSelf.labelOfTime2.text = [NSString stringWithFormat:@"%@",timeString];
    }];
}

//计算缓冲总进度
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    //获取缓冲区域
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    //计算缓冲总进度
    NSTimeInterval result = startSeconds + durationSeconds;
    return result;
}

#pragma mark - 用UISlider显示当前正在播放的进度
/** 这样UISlider就只有中间的ThumbImage了，而ThumbImage左右的颜色都变成透明的了，仅仅是用于显示当前的播放时间。UIProgressView则用于显示当前缓冲的区域，不做任何自定义的修改 */
- (void)customVideoSlider:(CMTime)duration {
    self.videoSlider = [[UISlider alloc]init];
    [self.videoSlider setThumbImage:[UIImage imageNamed:@"thumb1"] forState:UIControlStateNormal];
    [self addSubview:self.videoSlider];
    
    [self.videoSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(80);
        make.right.equalTo(self.mas_right).with.offset(-80);
        make.bottom.equalTo(self.mas_bottom).with.offset(-10);
        make.height.mas_equalTo(@15);
    }];
    
    if (duration.value) {
        
        self.videoSlider.maximumValue = CMTimeGetSeconds(duration);
    }
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self.videoSlider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
    [self.videoSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
    
    //slider滑动事件
    [self.videoSlider addTarget:self action:@selector(handleSlide:) forControlEvents:UIControlEventValueChanged];
    [self.videoSlider addTarget:self action:@selector(handleSlideEnd:) forControlEvents:UIControlEventValueChanged];
}

- (void)handleSlide:(UISlider *)sender{
    UISlider *slider = (UISlider *)sender;
    
    if (slider.value == 0.000000) {
        __weak typeof(self) weakSelf = self;
        [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            [weakSelf.player play];
        }];
    }
}

- (void)handleSlideEnd:(UISlider *)sender{
    UISlider *slider = (UISlider *)sender;
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        [weakSelf.player play];
        [weakSelf.buttonOfState setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    }];
}

#pragma mark - 播放/暂停按钮, 返回按钮 创建和点击事件
- (void)createButton{
    
    self.buttonOfState = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buttonOfState setBackgroundImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    [self addSubview:self.buttonOfState];
    
    [self.buttonOfState mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.center);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    [self.buttonOfState addTarget:self action:@selector(stateButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    
    self.buttonOfReturn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.buttonOfReturn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    self.buttonOfReturn.tintColor = [UIColor whiteColor];
    [self addSubview:self.buttonOfReturn];
    [self.buttonOfReturn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(20);
        make.top.equalTo(self.mas_top).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
//    self.buttonOfFullScreen = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.buttonOfFullScreen setBackgroundImage:[UIImage imageNamed:@"全屏"] forState:UIControlStateNormal];
//    [self addSubview:self.buttonOfFullScreen];
//    [self.buttonOfFullScreen mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.mas_left).with.offset(15);
//        make.bottom.equalTo(self.mas_bottom).with.offset(-8);
//        make.size.mas_equalTo(CGSizeMake(20, 20));
//    }];
//    [self.buttonOfFullScreen addTarget:self action:@selector(handleFullButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

//暂停播放按钮点击事件
- (void)stateButtonTouched:(UIButton *)button{
    if (_played) {
        [self.player play];
        [self.buttonOfState setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    } else {
        [self.player pause];
        [self.buttonOfState setBackgroundImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    }
    _played = !_played;
}

//全屏按钮点击事件
//- (void)handleFullButton:(UIButton *)button{
//    if (!button.selected) {
//        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
//    }else{
//        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
//        
//    }
//    button.selected = !button.selected;
//}


#pragma mark - 清晰度button
- (void)configDefinition{
    
    //一直显示的button
    self.buttonOfShow = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buttonOfShow setTitle:@"高清" forState:UIControlStateNormal];
    self.buttonOfShow.tintColor = [UIColor whiteColor];
    [self addSubview:self.buttonOfShow];
    [self.buttonOfShow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).with.offset(10);
        make.right.equalTo(self.mas_right).with.offset(-20);
        make.size.mas_equalTo(CGSizeMake(40, 30));
    }];
    [self.buttonOfShow addTarget:self action:@selector(handleButtonOfShow:) forControlEvents:UIControlEventTouchUpInside];
    
    //隐藏的button
    self.buttonOfHide = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buttonOfHide setTitle:@"标清" forState:UIControlStateNormal];
    self.buttonOfHide.tintColor = [UIColor whiteColor];
    [self addSubview:self.buttonOfHide];
    [self.buttonOfHide mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).with.offset(60);
        make.right.equalTo(self.mas_right).with.offset(-20);
        make.size.mas_equalTo(CGSizeMake(40, 30));
    }];
    self.buttonOfHide.hidden = YES;
    [self.buttonOfHide addTarget:self action:@selector(handleButtonOfHide:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)handleButtonOfShow:(UIButton *)button{
    if (!self.buttonOfShowisSelected) {
      
        self.buttonOfHide.hidden = NO;
    }else{
      
        self.buttonOfHide.hidden = YES;
        
    }
    self.buttonOfShowisSelected = !self.buttonOfShowisSelected;
}

- (void)handleButtonOfHide:(UIButton *)button{
    if (!button.selected) {
        [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
        [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:self.playerItem];
        [self.player removeTimeObserver:self.playbackTimeObserver];
        
            self.buttonOfHide.hidden = YES;

        [self.buttonOfShow setTitle:@"标清" forState:UIControlStateNormal];
        [self.buttonOfHide setTitle:@"高清" forState:UIControlStateNormal];
        self.playerItem = nil;
        [self.videoSlider removeFromSuperview];
        [self.videoProgress removeFromSuperview];
        [self.labelOfTime removeFromSuperview];
        [self.labelOfTime2 removeFromSuperview];
        self.videoSlider = nil;
        self.videoProgress = nil;
        self.labelOfTime =nil;
        self.labelOfTime2 = nil;
        [self cy_playerViewURl:[NSURL URLWithString:self.cy_mArrOfURL[0]]];
//         AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.cy_mArrOfURL[0]]];
//        
//        [self.player replaceCurrentItemWithPlayerItem:playerItem];
//        [self.player play];
        
            _played = !_played;
        
    }else{
        [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
        [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:self.playerItem];
        [self.player removeTimeObserver:self.playbackTimeObserver];
 
        self.buttonOfHide.hidden = YES;
        
        [self.buttonOfShow setTitle:@"高清" forState:UIControlStateNormal];
        [self.buttonOfHide setTitle:@"标清" forState:UIControlStateNormal];
        self.playerItem = nil;
        [self.videoSlider removeFromSuperview];
        [self.videoProgress removeFromSuperview];
        [self.labelOfTime removeFromSuperview];
        [self.labelOfTime2 removeFromSuperview];
        self.videoSlider = nil;
        self.videoProgress = nil;
        self.labelOfTime =nil;
        self.labelOfTime2 = nil;
        [self cy_playerViewURl:[NSURL URLWithString:self.cy_mArrOfURL[1]]];
         
        _played = !_played;
    }
    self.buttonOfShowisSelected = !self.buttonOfShowisSelected;
    button.selected = !button.selected;
}

#pragma mark - 下载button
- (void)configNextVideoButton{
    self.buttonOfDown = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buttonOfDown setBackgroundImage:[UIImage imageNamed:@"下载.png"] forState:UIControlStateNormal];
    [self addSubview:self.buttonOfDown];
    [self.buttonOfDown mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.mas_centerY);
        make.right.equalTo(self.mas_right).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    [self.buttonOfDown addTarget:self action:@selector(handleButtonOfNext:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)handleButtonOfNext:(UIButton *)sender{
    __weak UIButton *btn = sender;
    [[ZFDownloadManager sharedInstance] download:self.url.absoluteString progress:^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
        dispatch_async(dispatch_get_main_queue(), ^{ btn.enabled = NO; });
    } state:^(DownloadState state) {}];
    
}

#pragma mark -移除观察者,通知中心,avplayer!!!
- (void)dealloc {
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:self.playerItem];
    [self.player removeTimeObserver:self.playbackTimeObserver];
}


#pragma mark - UIPanGestureRecognizer手势方法

/**
 *  pan手势事件
 *
 *  @param pan UIPanGestureRecognizer
 */
- (void)panDirection:(UIPanGestureRecognizer *)pan
{
    //根据在view上Pan的位置，确定是调音量还是亮度
    CGPoint locationPoint = [pan locationInView:self];
    
    // 我们要响应水平移动和垂直移动
    // 根据上次和本次移动的位置，算出一个速率的point
    CGPoint veloctyPoint = [pan velocityInView:self];
    
    // 判断是垂直移动还是水平移动
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:{ // 开始移动
            // 使用绝对值来判断移动的方向
            CGFloat x = fabs(veloctyPoint.x);
            CGFloat y = fabs(veloctyPoint.y);
            if (x > y) { // 水平移动
                self.panDirection           = PanDirectionHorizontalMoved;
                //                // 取消隐藏
                self.labelOfMove.hidden = NO;
                // 给sumTime初值
                CMTime time                 = self.player.currentTime;
                self.sumTime                = time.value/time.timescale;
                
                // 暂停视频播放
                [self.player pause];
                // 暂停timer
                //                [self.timer setFireDate:[NSDate distantFuture]];
            }
            else if (x < y){ // 垂直移动
                self.panDirection = PanDirectionVerticalMoved;
                // 开始滑动的时候,状态改为正在控制音量
                if (locationPoint.x > self.bounds.size.width / 2) {
                    self.isVolume = YES;
                }else { // 状态改为显示亮度调节
                    self.isVolume = NO;
                }
            }
            break;
        }
        case UIGestureRecognizerStateChanged:{ // 正在移动
            switch (self.panDirection) {
                case PanDirectionHorizontalMoved:{
                    [self horizontalMoved:veloctyPoint.x]; // 水平移动的方法只要x方向的值
                    break;
                }
                case PanDirectionVerticalMoved:{
                    [self verticalMoved:veloctyPoint.y]; // 垂直移动方法只要y方向的值
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case UIGestureRecognizerStateEnded:{ // 移动停止
            // 移动结束也需要判断垂直或者平移
            // 比如水平移动结束时，要快进到指定位置，如果这里没有判断，当我们调节音量完之后，会出现屏幕跳动的bug
            switch (self.panDirection) {
                case PanDirectionHorizontalMoved:{
                    
                    // 继续播放
                    [self.player play];
                    //                    [self.timer setFireDate:[NSDate date]];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        // 隐藏视图
                        self.labelOfMove.hidden = YES;
                    });
                   
                    CMTime dragedCMTime = CMTimeMake(self.sumTime, 1);
                    [self.player seekToTime:dragedCMTime];
                    // 把sumTime滞空，不然会越加越多
                    self.sumTime = 0;
                    break;
                }
                case PanDirectionVerticalMoved:{
                    // 垂直移动结束后，把状态改为不再控制音量
                    self.isVolume = NO;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        self.labelOfMove.hidden = YES;
                    });
                    break;
                }
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
}

/**
 *  pan垂直移动的方法
 *
 *  @param value void
 */
- (void)verticalMoved:(CGFloat)value
{
    if (self.isVolume) {
        // 更改系统的音量
        self.volumeViewSlider.value      -= value / 10000;// 越小幅度越小
    }else {
        //亮度
        [UIScreen mainScreen].brightness -= value / 10000;
    }
}

/**
 *  pan水平移动的方法
 *
 *  @param value void
 */
- (void)horizontalMoved:(CGFloat)value
{
    // 快进快退的方法
    NSString *style = @"";
    if (value < 0) {
        style = @"<<";
    }
    else if (value > 0){
        style = @">>";
    }
    // 每次滑动需要叠加时间
    self.sumTime += value / 200;
    
    // 需要限定sumTime的范围
    CMTime totalTime           = self.playerItem.duration;
    CGFloat totalMovieDuration = (CGFloat)totalTime.value/totalTime.timescale;
    if (self.sumTime > totalMovieDuration) {
        self.sumTime = totalMovieDuration;
    }else if (self.sumTime < 0){
        self.sumTime = 0;
    }
    
    //    // 当前快进的时间
    NSString *nowTime         = [self convertTime:self.sumTime];
    // 总时间
    NSString *durationTime    = [self convertTime:totalMovieDuration];
    //    // 给label赋值
    self.labelOfMove.text = [NSString stringWithFormat:@"%@ %@ / %@",style, nowTime, durationTime];
   
}


- (void)configureVolume
{
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    _volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            _volumeViewSlider = (UISlider *)view;
            break;
        }
    }
}


@end
